<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        div{padding:10px;}
        img{width:100px;}
    </style>
</head>
<body>
    
</body>
<script>
    // 组合器

    // 枝对象的工厂
    function Team(id){
        this.ele = document.createElement("div");
        this.ele.id = id;
        this.children = [];
    }
    Team.prototype.add = function(child){
        this.children.push(child);
        this.ele.appendChild(child.ele);
    }
    Team.prototype.remove = function(child){
        this.ele.removeChild( child.ele );
        let i = 0;
        const flag = this.children.some((val,idx)=>{
            i = idx;
            return val === child;
        });
        flag && this.children.splice(i, 1);
    }
    // 具体的操作...
    Team.prototype.addBorder = function(child){
        this.ele.style.border = "solid 4px black";
        this.children.forEach(val=>val.addBorder());
    }
    Team.prototype.removeBorder = function(child){
        this.ele.style.border = "";
        this.children.forEach(val=>val.removeBorder());
    }

    // 叶对象的工厂
    function Item(src){
        this.ele = document.createElement("img");
        this.ele.src = src;
    }
    Item.prototype.add = function(child){
        console.log("这是一个叶对象，不能添加子对象")
    }
    Item.prototype.remove = function(child){
        console.log("这是一个叶对象，没有子对象可被删除")
    }
    Item.prototype.addBorder = function(child){
        this.ele.style.border = "solid 4px pink";
    }
    Item.prototype.removeBorder = function(child){
        this.ele.style.border = "";
    }

    const root = new Team("box");
    document.body.appendChild(root.ele);

    const box1 = new Team("box1");
    root.add(box1);

    const box2 = new Team("box2");
    root.add(box2);

    const xbox = new Team("xbox");
    box1.add(xbox)

    // root.remove(box1);

    const img1 = new Item("https://img2.baidu.com/it/u=2248863795,4033026016&fm=253&app=120&size=w931&n=0&f=JPEG&fmt=auto?sec=1667494800&t=b50a8a10e8beb77a642c018874a4a755");
    const img2 = new Item("https://img2.baidu.com/it/u=4029214852,4040556744&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1667494800&t=4a19dbe3454b479079d0e24857d5453f");
    const img3 = new Item("https://img2.baidu.com/it/u=3633522105,3327760635&fm=253&app=138&size=w931&n=0&f=JPEG&fmt=auto?sec=1667494800&t=e28cc90e88223bc23b1f5ed1e4ee50f1");
    const img4 = new Item("https://t9.baidu.com/it/u=3659822642,593310920&fm=218&app=126&size=f242,150&n=0&f=JPEG&fmt=auto?s=7F1506C6CDA90126543AF0390300D019&sec=1667494800&t=9061544f90163b317f9a352c8e2c0ac5");

    root.add(img1);
    box2.add(img2);
    box1.add(img3);
    xbox.add(img4);

    // 以上只是组合
    // box
    //     box1
    //         xbox
    //             img
    //         img
    //     box2
    //         img
    //     img

    root.addBorder();
    // box1.addBorder();

    // img4.addBorder();

    box2.removeBorder();

    img4.removeBorder();



</script>
</html>